/*
 * Copyright (C) 2010-2011 Comcast Cable.  All Rights Reserved.
 */
package com.hercules.android.receiver.painting.resources;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;

import com.hercules.android.receiver.AndroidReceiver;
import com.hercules.android.receiver.LogUtil;
import com.hercules.android.receiver.handlers.events.EventRaisingException;
import com.hercules.android.receiver.model.events.XREStreamPlaybackStateEvent;
import com.hercules.android.receiver.model.objects.XRESound;
import com.hercules.android.receiver.painting.PaintersUtil;
import com.hercules.android.receiver.painting.XREObjectPainterException;
import com.hercules.android.receiver.painting.views.AndroidXREView;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * Utility used to initialize and finish media players.
 * <p>
 * AndroidAssembly2 this class was added in Android Assembly 2
 * <p>
 * <b>Thread safety:</b> Is immutable and thread safe.
 *
 * @author 7realm
 * @version 1.0
 */
public class XRESoundUtil {
    /** Represents logger, used for logging. */
    private static final Logger LOGGER = Logger.getLogger(XRESoundUtil.class.getSimpleName());
    /** Represents instance, used for logging. */
    private static final Object INSTANCE = new XRESoundUtil();

    /**
     * Constructor for class XRESoundUtil.
     */
    private XRESoundUtil() {
        // empty
    }

    /**
     * Performs initialize actions.
     *
     * @param receiver the android receiver
     * @param sound the sound to init
     * @throws IllegalArgumentException if any parameter is null
     * @throws XREObjectPainterException if error occurs while setup
     */
    @SuppressWarnings("boxing")
    public static void init(final AndroidReceiver receiver, final XRESound sound) throws XREObjectPainterException {
        final String methodName = "init";
        LogUtil.enter(LOGGER, INSTANCE, methodName, receiver, sound);

        try {
            PaintersUtil.checkNull(receiver, "receiver");
            PaintersUtil.checkNull(sound, "sound");
/*
            // setup the media player
            MediaPlayer mp = new MediaPlayer();
            try {
                // set data source
                mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mp.setDataSource(sound.getUrl());
                mp.prepareAsync();

                mp.setOnErrorListener(new OnErrorListener() {
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        return false;
                    }
                });

                mp.setOnPreparedListener(new OnPreparedListener() {
                    public void onPrepared(MediaPlayer mp) {
                        // If autoplay is on, play the audio
                        if (sound.isAutoPlay()) {
                            mp.start();
                        }
                    }
                });

                mp.setOnCompletionListener(new OnCompletionListener() {
                    public void onCompletion(MediaPlayer mp) {
                        XREStreamPlaybackStateEvent event = new XREStreamPlaybackStateEvent();
                        event.setName(XREStreamPlaybackStateEvent.ON_STREAM_COMPLETE_EVENT_NAME);
                        event.setSource(sound.getId());

                        try {
                            // raise error
                            AndroidXREView.getEventRaiser().raiseEvent(event, receiver, true);
                        } catch (EventRaisingException e) {
                            LogUtil.error(LOGGER, INSTANCE, methodName, e);
                        }
                    }
                });
            } catch (IOException e) {
                throw new XREObjectPainterException("Cannot set data source to media player, I/O error occurred.", e);
            }

            // set the volume
            mp.setVolume(sound.getVolume(), sound.getVolume());

            // add player to extra painter map
            PaintersUtil.getPainterDataMap(receiver, "mediaPlayers").put(sound.getId(), mp);*/
        } catch (IllegalArgumentException e) {
            throw LogUtil.error(LOGGER, INSTANCE, methodName, e);
        }/* catch (XREObjectPainterException e) {
            throw LogUtil.error(LOGGER, INSTANCE, methodName, e);
        }*/

        LogUtil.exit(LOGGER, INSTANCE, methodName);
    }

    /**
     * Performs clean up.
     *
     * @param receiver the android receiver
     * @param sound the sound to finish
     * @throws IllegalStateException if required fields are not set
     * @throws XREObjectPainterException if error occurs while clean up
     */
    @SuppressWarnings("boxing")
    public static void finish(AndroidReceiver receiver, XRESound sound) throws XREObjectPainterException {
        String methodName = "finish";
        LogUtil.enter(LOGGER, INSTANCE, methodName, receiver, sound);

        try {
            PaintersUtil.checkNull(receiver, "receiver");
            PaintersUtil.checkNull(sound, "sound");

            // get player from extra painter map
            MediaPlayer mp =
                PaintersUtil.getPainterDataValue(receiver, "mediaPlayers", sound.getId(), MediaPlayer.class);

            // remove player from extra painter map
            PaintersUtil.getPainterDataMap(receiver, "mediaPlayers").remove(sound.getId());

            // stop and release the audio
            mp.stop();
            mp.release();
        } catch (IllegalArgumentException e) {
            throw LogUtil.error(LOGGER, INSTANCE, methodName, e);
        } catch (XREObjectPainterException e) {
            throw LogUtil.error(LOGGER, INSTANCE, methodName, e);
        }

        LogUtil.exit(LOGGER, INSTANCE, methodName);
    }
}
